from django.db import models
from datetime import date


# 定义图书模型类
class BookInfo(models.Model):
    btitle = models.CharField(max_length=20, verbose_name='名称')
    bpub_data = models.DateField(verbose_name='发布日期')
    bread = models.IntegerField(default=0, verbose_name='阅读量')
    bcomment = models.IntegerField(default=0, verbose_name='评论量')
    is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')

    # 添加一个ImageField类型字段 upload_to 选项指明该字段的图片保存在MEDIA_ROOT
    # 目录中的哪个子目录 即具体的存放目录
    image = models.ImageField(upload_to="booktest", verbose_name="图片", null=True)

    class Meta:
        db_table = 'tb_books'  # 指明数据库表名
        verbose_name = '图书'  # 在admin站点中显示的名称
        verbose_name_plural = verbose_name  # 显示的复数名称

    def __str__(self):
        """定义每个数据对象的显示信息"""
        return self.btitle

    def pub_date_format(self):
        """返回指定格式日期"""
        return self.bpub_data.strftime("%Y-%m-%d")

    # 设置方法字段在admin中显示的 标题
    pub_date_format.short_description = "发布日期"
    # 依照此方法设置排序
    pub_date_format.admin_order_field = "bpub_data"


# 定义英雄模型类
class HeroInfo(models.Model):

    GENDER_CHOICES = (
        (0, 'female'),
        (1, 'male')
    )

    hname = models.CharField(max_length=20, verbose_name='名称')
    hgender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='性别')
    hcomment = models.CharField(max_length=200, null=True, verbose_name="描述信息")
    hbook = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name="图书")
    is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = "tb_hero"
        verbose_name = "英雄"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.hname

    def book_read(self):
        """返回英雄所在书籍的阅读量"""
        return self.hbook.bread

    book_read.short_description = "阅读量"
    book_read.admin_order_field = hbook